<?php

namespace app\api\controller\user;

use app\api\model\common\CoinModel;
use app\api\model\user\UserAddressModel;
use app\api\model\user\UserAssetsLogModel;
use app\api\model\user\UserAssetsModel;
use app\api\request\user\UserAddressRequest;
use app\common\controller\Api;
use app\common\library\Ems;
use think\Exception;
use think\Loader;

class UserAddress extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];


    /**
     * Notes: 钱包地址信息
     * User: 浪子膏
     * Date: 2023/11/1 16:20
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function list()
    {
        $userAddressModel = new UserAddressModel();
        $coinModel = new CoinModel();
        $list = $userAddressModel->where('user_id', $this->auth->id)->field('id,user_id,address,type')
            ->select();

        foreach ($list as &$item){
            if($item['type'] == 'usdt'){
                $item['avatar'] = Https(config('site.usdt_avatar'));
            }else{
                $item['avatar'] = Https($coinModel->where('coin_type',ucwords($item['type']))->value('avatar'));
            }
        }

        $this->dataOk($list);
    }

    /**
     * Notes: 绑定钱包地址
     * User: 浪子膏
     * Date: 2023/11/2 09:30
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */

    public function bind()
    {
        $params = request()->post();
        $validate = Loader::validate(UserAddressRequest::class);
        if (!$validate->scene('bind')->check($params)) $this->error($validate->getError());

        $userAddressModel = new UserAddressModel();
        $info = $userAddressModel->where(['user_id' => $this->auth->id, 'id' => $params['id']])->find();
        if (empty($info)) {
            $this->error(__('That information no longer exists'));
        }

        $email = $this->auth->getUser()['username'];
        $result = Ems::check($email, $params['captcha'], 'bind');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }

        try {
            $userAddressModel->startTrans();
            $info->address = $params['address'];
            $info->save();

            Ems::flush($email, 'bind');
            $userAddressModel->commit();
        } catch (Exception $exception) {
            $userAddressModel->rollback();
            $this->error($exception->getMessage());
        }

        $this->success();

    }




}